package cn.imvc.app.models;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.entities.Bankcard;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.BankcardRepository;
import cn.imvc.core.ICache;
import cn.imvc.data.domain.ViewRequest;

@Service
public class BankcardModelImpl implements BankcardModel {

	@Autowired
	private BankcardRepository bankcardRepository;

	@Autowired
	DealerApplyModel dealerApplyModel;

	@Autowired
	MemberModel memberModel;

	@Autowired
	ICache cache;
	
	@Autowired
	SystemConfig systemConfig;


	public Bankcard get(int id) {
		return bankcardRepository.findOne(id);
	}

	public Page<Bankcard> find(ViewRequest viewRequest) {
		return (Page<Bankcard>) bankcardRepository.findAll();
	}

	public Bankcard save(Bankcard Bankcard) {

		Bankcard Bankcard2 = bankcardRepository.saveAndFlush(Bankcard);

		return Bankcard2;
	}

	public Bankcard update(Bankcard newBankcard) {
		Bankcard loadBankcard = get(newBankcard.getId());
		BeanUtils.copyProperties(newBankcard, loadBankcard, new String[] { "id" });

		return bankcardRepository.saveAndFlush(loadBankcard);
	}

	public void delete(int id) {
		bankcardRepository.delete(id);

	}

	public void deleteBatch(int[] ids) {

		for (int id : ids) {
			delete(id);
		}

	}
	
	public Bankcard findDefaultCard(Integer memberId,Byte isDefault){
		
		return bankcardRepository.findBymemberIdAndIsDefault(memberId, isDefault);
	}
	
	public void cancelDefault(Member member){
		Bankcard bankcard =findDefaultCard(member.getId(), (byte)1);
		if (bankcard==null){
			return;
		}
		bankcard.setIsDefault((byte)0);
		save(bankcard);
	}

}
